// 检查登录状态
function checkAuth() {
    const token = localStorage.getItem('token');
    const protectedPaths = ['/write', '/profile'];
    
    if (protectedPaths.includes(window.location.pathname)) {
        if (!token) {
            // 保存当前页面路径
            localStorage.setItem('redirectUrl', window.location.pathname);
            window.location.href = '/login';
            return;
        }
        
        // 验证token
        fetch('/api/auth/check', {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Token验证失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.code !== 200) {
                throw new Error(data.message || 'Token验证失败');
            }
        })
        .catch(() => {
            localStorage.removeItem('token');
            localStorage.setItem('redirectUrl', window.location.pathname);
            window.location.href = '/login';
        });
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 显示提示消息
function showMessage(message, type = 'success') {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.setAttribute('role', 'alert');
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const container = document.querySelector('.container');
    container.insertBefore(alertDiv, container.firstChild);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    checkAuth();
    
    // 为所有需要确认的操作添加确认对话框
    document.querySelectorAll('[data-confirm]').forEach(element => {
        element.addEventListener('click', function(e) {
            if (!confirm(this.dataset.confirm)) {
                e.preventDefault();
            }
        });
    });
});

// 获取JWT token
function getToken() {
    return localStorage.getItem('token');
}

// 处理登录成功后的重定向
function handleLoginRedirect() {
    const redirectUrl = localStorage.getItem('redirectUrl');
    if (redirectUrl) {
        localStorage.removeItem('redirectUrl');
        window.location.href = redirectUrl;
    } else {
        window.location.href = '/';
    }
} 